<template>
    <div class="friend_circle_sop_container">
        <!-- 搜索栏 -->
        <ZwSearchForm row-num="4" :option="searchOption" @search="search" @reset="reset" @expand="getTableH" />
        <ZwTable
            ref="tableRef"
            class="table-box"
            :option="tableOption"
            :fetch-params="state.searchParams"
            :fetch-api="fetch()">
            <template #headerOperate>
                <el-button v-auth="'REMIND_RULE_SET'" @click="createSet">提醒规则设置</el-button>
                <el-button v-auth="'ADVANCED_SET'" @click="heightSet">高级设置</el-button>
                <el-button v-auth="'SYNC_EXTER_CONTACT'" @click="async">同步配置了外部联系权限的联系人</el-button>
                <el-button
                    v-auth="'FRIEND_CIRCLE_CREATE_SOP'"
                    type="primary"
                    @click="router.push('/smartMarketing/marketAutomation/friendCircleSop/createSop')">
                    创建SOP规则
                </el-button>
            </template>
        </ZwTable>
        <Createset ref="Createref"></Createset>
        <Heightset ref="Heightref"></Heightset>
        <Drawer ref="Drawerref"></Drawer>
        <Dialog :app-dialog="delDialog">
            <div class="title">确定要删除该SOP规则吗?</div>
        </Dialog>
    </div>
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'FRIEND_CIRCLE_SOP' });
</script>

<script lang="tsx" setup>
import { ref, reactive, computed, nextTick, onActivated } from 'vue';
import router from '@/router';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import Createset from './components/Createset.vue';
import Heightset from './components/Heightset.vue';
import Drawer from './components/Drawer.vue';
import { dividerProps, ElButton, ElMessage, ElPopover } from 'element-plus';
import Dialog from '@/components/Dialog.vue';
import { deepCopy } from '@/utils/helper';
import { getsopList, change, del, asyncData, getlist } from '@/api/smartMarketing/marketAutomation/friendCircleSop';
import { getCreateList } from '@/api/common';

const Createref = ref(null);
const tableRef = ref(null);
const Heightref = ref(null);
const Drawerref = ref(null);
const defaultParams = {};
const sopRuleId = ref();
const requestFlag = ref<boolean>(false);
const currentParams = ref<any>(null);
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
// 获取表格高度
const getTableH = () => {
    nextTick(() => {
        tableRef.value.getTableH();
    });
};
const sopBtnList = reactive([
    { id: 1, val: '开启', auth: 'OPEN_FRIEND_SOP' },
    { id: 0, val: '关闭', auth: 'CLOSE_FRIEND_SOP' },
    { id: 3, val: '查看', auth: 'LOOK_FRIEND_SOP' },
    { id: 4, val: '编辑', auth: 'EDIT_FRIEND_SOP' },
    { id: 5, val: '删除', auth: 'DEL_FRIEND_SOP' }
]);
const searchOption = computed(() => {
    return [
        {
            label: '规则名称',
            name: 'keyword',
            value: '',
            type: 'input',
            placeholder: '请输入名称搜索'
        },
        {
            label: '创建人',
            name: 'create_workuser_list',
            value: [],
            multiple: true,
            type: 'select',
            filterable: true,
            placeholder: '全部',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const targetArr = res.map((item: any) => {
                            item.name = `${item.name}  (${item.phone})`;
                            return item;
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '执行人',
            name: 'execute_workuser_list',
            value: [],
            type: 'select',
            placeholder: '全部',
            multiple: true,
            popperClass: 'zw-hide_select_option',
            isUserSelect: true,
            formatOption: v => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '质检人',
            name: 'qa_workuser_list',
            value: [],
            type: 'select',
            placeholder: '全部',
            multiple: true,
            popperClass: 'zw-hide_select_option',
            isUserSelect: true,
            formatOption: v => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: 'SOP状态',
            name: 'status',
            value: '',
            type: 'select',
            placeholder: '全部',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve([
                        { name: '全部', id: '' },
                        { name: '开启', id: '1' },
                        { name: '关闭', id: '0' }
                    ]);
                });
            },
            formatOption: v => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '创建时间',
            name: 'create_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        }
    ];
});

const tableOption = [
    {
        prop: 'title',
        label: '规则名称',
        minWidth: 240
    },
    {
        prop: 'cycle_type',
        label: '类型',
        minWidth: 240,
        showOverflowTooltip: true,
        render({ row, column, index }) {
            let text: any = '';
            const detailText: any = [];
            text = row.cycle_type == 1 ? '每日推送' : row.cycle_type == 2 ? '每周推送' : '每月推送';
            if (row.personal_times != 0) {
                detailText.push(row.personal_times + '篇个人微信朋友圈');
            }
            if (row.corporate_times != 0) {
                detailText.push(row.corporate_times + '篇企业微信朋友圈');
            }
            return text + '(' + detailText.join('、') + ')';
        }
    },
    {
        prop: 'created_name',
        label: '创建人',
        width: 120
    },
    {
        label: '执行人',
        prop: 'execute_workuser',
        width: 200,
        showOverflowTooltip: true,
        render({ row, column, index }) {
            const slotReference = () => (
                <div>
                    {row.execute_workuser.map((item: any, index: any) => {
                        return (
                            <span>
                                {item.name}
                                <span v-show={row.execute_workuser.length - 1 !== index}>、</span>
                            </span>
                        );
                    })}
                </div>
            );
            const slotDefault = () => (
                <div>
                    {row.execute_workuser.map((item: any, index: any) => {
                        return (
                            <span>
                                {item.name}
                                <span v-show={row.execute_workuser.length - 1 !== index}>、</span>
                            </span>
                        );
                    })}
                </div>
            );
            return (
                <div>
                    <div v-show={row.execute_workuser.length <= 8}>
                        {row.execute_workuser.map((item: any, index: any) => {
                            return (
                                <span>
                                    {item.name}
                                    <span v-show={row.execute_workuser.length - 1 !== index}>、</span>
                                </span>
                            );
                        })}
                    </div>
                    <div v-show={row.execute_workuser.length > 8}>
                        <ElPopover
                            popper-class="popGroup"
                            trigger="hover"
                            vSlots={{ reference: slotReference, default: slotDefault }}
                            width={300}
                            popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"></ElPopover>
                    </div>
                </div>
            );
        }
    },
    {
        prop: 'qa_workuser',
        label: '质检人',
        width: 200,
        showOverflowTooltip: true,
        render({ row, column, index }) {
            const slotReference = () => (
                <div>
                    {row.qa_workuser.map((item: any, index: any) => {
                        return (
                            <span>
                                {item.name}
                                <span v-show={row.qa_workuser.length - 1 !== index}>、</span>
                            </span>
                        );
                    })}
                </div>
            );
            const slotDefault = () => (
                <div>
                    {row.qa_workuser.map((item: any, index: any) => {
                        return (
                            <span>
                                {item.name}
                                <span v-show={row.qa_workuser.length - 1 !== index}>、</span>
                            </span>
                        );
                    })}
                </div>
            );
            return (
                <div>
                    <div v-show={row.qa_workuser.length <= 8}>
                        {row.qa_workuser.map((item: any, index: any) => {
                            return (
                                <span>
                                    {item.name}
                                    <span v-show={row.qa_workuser.length - 1 !== index}>、</span>
                                </span>
                            );
                        })}
                    </div>
                    <div v-show={row.qa_workuser.length > 8}>
                        <ElPopover
                            popper-class="popGroup"
                            trigger="hover"
                            vSlots={{ reference: slotReference, default: slotDefault }}
                            width={300}
                            popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"></ElPopover>
                    </div>
                </div>
            );
        }
    },
    {
        prop: 'status',
        label: 'SOP状态',
        width: 200,
        render({ row }) {
            return (
                <div>
                    <p>{row.status == 1 ? <span style="color:#60B900">已开启</span> : '已关闭'}</p>
                </div>
            );
        }
    },
    {
        prop: 'created_at',
        label: '创建时间',
        width: 200
    },
    {
        prop: 'operate',
        label: '操作',
        width: 260,
        fixed: 'right',
        isOperate: true,
        renderOperate({ row, column, index }) {
            return sopBtnList.map((item: any, index: number) => {
                return (
                    <>
                        <ElButton
                            size="small"
                            v-show={item.id != row.status}
                            v-auth={item.auth}
                            disabled={item.id == 4 && row.status == 1}
                            onClick={() => sopBtn(row, item.id)}>
                            {item.val}
                        </ElButton>
                    </>
                );
            });
        }
    }
];
const sopBtn = (row: any, num: any) => {
    const status = (number: any) => {
        const params = {
            id: row.id,
            status: number
        };
        change(params)
            .then((res: any) => {
                tableRef.value.reload();
                ElMessage.success('SOP状态修改成功');
            })
            .catch((e: any) => {
                ElMessage.error('SOP状态修改失败');
            });
    };
    switch (num) {
        case 1:
            status(1);
            break;
        case 0:
            status(0);
            break;
        case 3:
            Drawerref.value.id = row.id;
            Drawerref.value.open(row);
            break;
        case 4:
            router.push('/smartMarketing/marketAutomation/friendCircleSop/editsSop?id=' + row.id);
            break;
        case 5:
            sopRuleId.value = row.id;
            delDialog.visible = true;
            break;
    }
};
const cancelHandel = () => {
    delDialog.visible = false;
};
const submitHandel = () => {
    del({ id: sopRuleId.value })
        .then((res: any) => {
            cancelHandel();
            tableRef.value.reload();
            ElMessage.success('删除成功');
        })
        .catch((e: any) => {
            ElMessage.error('删除失败');
        });
};
// 弹框配置项
const delDialog = reactive({
    visible: false,
    title: '提示',
    width: '30%',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定',
    isInit: false, //是否重置
    isChooseDisabled: false, //重新打开传递进来的数据是否重置
    chooseArr: [] // 传递进来选中的数据
});
// 设置规则
const createSet = () => {
    Createref.value.appDialog.visible = true;
};
//高级设置
const heightSet = () => {
    Heightref.value.appDialog.visible = true;
};
//查询
const search = v => {
    currentParams.value = v;
    state.searchParams = v;
};
const reset = v => {
    state.searchParams = deepCopy(defaultParams);
    currentParams.value = null;
};
const fetch = () => {
    return getsopList;
};
//同步联系人
const async = () => {
    asyncData()
        .then((res: any) => {
            ElMessage.success('同步成功');
        })
        .catch((err: any) => {
            ElMessage.error(err);
        });
};
onActivated((val: any) => {
    state.searchParams = { ...deepCopy(defaultParams), ...currentParams.value };
});
</script>
<style lang="scss" scoped>
.friend_circle_sop_container {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }
}

:deep .sopBtn {
    padding: 4px 16px;
    margin: 3px;
    min-height: 0;
    border-radius: 2px;
    border: 1px solid #eaeaea;
}

.title {
    text-align: center;
    padding: 50px 0;
}
</style>
